package handler

import (
	"github.com/gin-gonic/gin"
	"house/api/request"
	"house/api/resp"
	"house/consts"
	"house/internal/dao"
	"house/internal/model"
	"house/internal/queue"
	"house/pkg"
)

func AddHouse(c *gin.Context) {
	var req request.AddHouse
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "验证失败", err.Error())
		return
	}
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if !(user.TypeUser == 2 || user.TypeUser == 3) {
		resp.Error(c, 100000, "您没有权限发布房源", false)
		return
	}
	if !TextCensor(req.Title, c.GetUint("userId"), "发布房源") {
		resp.Error(c, 100000, "房源信息有敏感字", false)
		return
	}

	result := dao.Create(&model.House{
		Title:     req.Title,
		Price:     req.Price,
		Area:      req.Area,
		City:      req.City,
		Address:   req.Address,
		Community: req.Community,
		ImgUrl:    req.ImgUrl,
		VideoUrl:  req.VideoUrl,
		UserId:    c.GetUint("userId"),
	})

	if !result {
		resp.Error(c, 100000, "房源发布失败", false)
		return
	}
	resp.Success(c, "房源发布成功", true)
}

func TextCensor(content string, userId uint, bName string) bool {
	if pkg.TextCensor(content) {
		return true
	}
	dao.Create(&model.Safe{
		UserId:  userId,
		Content: content,
		BName:   bName,
	})
	return false
}

func ListHouse(c *gin.Context) {
	var req request.ListHouse
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "验证失败", err.Error())
		return
	}
	dto := dao.PageDto{
		Page:     req.Page,
		PageSize: req.PageSize,
	}
	var house []model.House

	paginate, err := dao.Paginate(&model.House{
		Title: req.Title,
	}, dto, &house)

	if err != nil {
		resp.Error(c, 100000, "房源列表展示失败", err.Error())
		return
	}
	resp.Success(c, "房源展示成功", paginate)
}

func Detail(c *gin.Context) {
	var req request.Detail
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "验证失败", err.Error())
		return
	}
	var house model.House
	dao.GetOneById(req.Id, &house)
	if house.Id == 0 {
		resp.Error(c, 100000, "该房源不存在", false)
		return
	}
	resp.Success(c, "房源详情查看成功", house)
}

func UpdateHouse(c *gin.Context) {
	var req request.UpdateHouse
	if err := c.ShouldBind(&req); err != nil {
		resp.Error(c, 100000, "验证失败", err.Error())
		return
	}
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if !(user.TypeUser == 2 || user.TypeUser == 3) {
		resp.Error(c, 100000, "您没有权限修改房源", false)
		return
	}
	var house model.House
	dao.GetOneById(req.Id, &house)
	if house.Id == 0 {
		resp.Error(c, 100000, "该房源不存在", false)
		return
	}
	if req.Price > 0 && (req.Price != house.Price) {
		go queue.PublishPub(consts.Admin_broadcast, &model.House{
			Id:    req.Id,
			Title: house.Title,
			Price: req.Price,
		})
	}

	result := dao.Update(&model.House{
		Id:    req.Id,
		Price: req.Price,
	})

	if !result {
		resp.Error(c, 100000, "房源价格修改失败", false)
		return
	}
	resp.Success(c, "房源价格修改成功", true)
}
